<?php

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use framework\libraries\ErrorType;
use framework\libraries\Stdio;
use framework\support\Model;
use framework\support\Redis;
use framework\support\Response;

class admin
{
    function before()
    {
        $request = request();
        $authHeader = $request->header("Authorization");
        $token = null;
        if ($authHeader) {
            $arr = explode(' ', $authHeader);
            if (count($arr) > 1) {
                $token = $arr[1];
            } else {
                $token = $authHeader;
            }
        }
        $key = $_ENV['ADMIN_SECRET_KEY'] ?? 'WeeSpeed@admin';
        try {
            $jwtData = JWT::decode($token, new Key($key, 'HS256'));
            if ($jwtData->expire < time()) {
                Response::Raw(401, "令牌过期");
                return false;
            }
            $admin = Model::getItemByID('admin', $jwtData->aid, false, 'id', null);
            if (!$admin) {
                return new Response(200, ['Content-Type' => 'application/json'], json_encode([
                    'code' => ErrorType::NOT_EXISTS,
                    'msg' => ErrorType::messages[ErrorType::NOT_EXISTS]
                ]));
            }
            if ($admin['is_banned']) {
                return new Response(200, ['Content-Type' => 'application/json'], json_encode([
                    'code' => ErrorType::ACCOUNT_DISABLED,
                    'msg' => ErrorType::messages[ErrorType::ACCOUNT_DISABLED]
                ]));
            }
            $request->data('uid', $jwtData->aid);
            $request->data('admin', $admin);
        } catch (SignatureInvalidException $e) {
            Stdio::error("token " . $e->getMessage());
            Response::Raw(401, "令牌无效");
            return false;
        } catch (\Exception $e) {
            Stdio::error("token " . $e->getMessage());
            Response::Raw(401, "令牌解析失败");
            return false;
        }
    }

    function after()
    {
        //print("do after");
    }
}
